<?php

namespace app\admin\controller;

use app\admin\model\bin\Native;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use app\admin\model\bin\Type;
use think\paginator\driver\Bootstrap;

/**
 * 堆场
 *
 * @icon fa fa-circle-o
 */
class Organization extends Backend
{

    /**
     * Organization模型对象
     * @var \app\admin\model\Organization
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Organization;
        $this->view->assign("organTypeList", $this->model->getOrganTypeList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $organ_type=1;
            if(!empty(input('organ_type'))){
                $organ_type=input('organ_type');
            }
            $this->assign("organ_type",$organ_type);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['organ_sn']='O'.substr(md5(microtime(true)), 0, 9);

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /*
      * 相应箱型下面对应的堆场可用箱数量
      */
    public function bin_type_yard(){
        $this->request->filter(['strip_tags','trim']);
        $params =$this->request->param();
        //如果发送的来源是Selectpage，则转发到Selectpage
        $where1=[];
        $bin_type_name='';
        $bin_native_name='';
        $real_where1=[];
        $real_where1['bin_origin']=$params['custom']['bin_origin'];
        $real_where1['current_status']=1;


        if(!empty($params['custom']['bin_type'])) {
            $bin_type = $params['custom']['bin_type'];
            $bin_type_name = Type::where(['id' => $bin_type])->value('name');
            $real_where1['bin_type'] = $params['custom']['bin_type'];
        }
        if(!empty($params['custom']['bin_native'])){
            $bin_native=$params['custom']['bin_native'];
            $bin_native_name= Native::where(['id'=>$bin_native])->value('name');
            $real_where1['bin_native']=$params['custom']['bin_native'];
        }
        if(!empty($params['custom']['organ_type'])){
            $where1['organ_type']=$params['custom']['organ_type'];
        }
        if(!empty($params['organ_name'])){
            $where1['organ_name']=['like','%'.$params['organ_name'].'%'];
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        // 排序
        $page=1;
        $pageSize=10;
        if(!empty($params['pageNumber'])){
            $page=$params['pageNumber'];
        }
        if(!empty($params['pageSize'])) {
            $pageSize = $params['pageSize'];
        }
       /* //总数
        $total = $this->model
            ->where($where1)
            ->count();*/

        //这个分页的数据
        $list = $this->model
            ->field('id,organ_name')
            ->with([
                'bin'=>function($query)use($real_where1){$query->where($real_where1);},
            ])
            ->where($where1)
            ->select();
        $json = json_encode((object)$list);
        $lists = json_decode($json, true);

        foreach ($lists as $k=> &$vo){
           $vo['bin_number']=count($vo['bin']);
           $vo['bin_type_name']=$bin_type_name;
           $vo['bin_native_name']=$bin_native_name;
            if($params['custom']['bin_origin']==1){
                $vo['bin_origin_name']='自备箱';
            }else if ($params['custom']['bin_origin']==2){
                $vo['bin_origin_name']='租赁箱';
            }
        }

        $bin_number = array_column($lists,'bin_number');//返回数组中指定的一列
        $ids = array_column($lists,'id');//返回数组中指定的一列
        array_multisort($bin_number,SORT_DESC,$ids,SORT_ASC,$lists);//对多个数组或多维数组进行排序
       /*
        * 过滤箱子是空的数组
        */
        $filteredLists=array_filter($lists,function ($v){
            return !empty($v['bin']);
        });

        //数组根据当前页码和每页数据获取当前页的数据
        $start=($page-1)*$pageSize;
        $filteredData=array_slice($filteredLists,$start,$pageSize);


        $result = ['total' => count($filteredLists), 'list' => $filteredData];
        return json($result);

    }

    /*
     * 箱公司的箱子数据
     */
    public function bin_company_data(){
        $this->request->filter(['strip_tags','trim']);
        $params =$this->request->param();
        //如果发送的来源是Selectpage，则转发到Selectpage
        $real_where1=[];
        $where1=[];

        if(!empty($params['custom']['organ_type'])){
            $where1['organ_type']=$params['custom']['organ_type'];
            $real_where1['bin_origin']=2;
            $real_where1['current_status']=1;
        }
        $page=1;
        $pageSize=10;
        if(!empty($params['pageNumber'])){
            $page=$params['pageNumber'];
        }
        if(!empty($params['pageSize'])) {
            $pageSize = $params['pageSize'];
        }
      /*  $page=$params['pageNumber'];
        $pageSize=$params['pageSize'];*/

        //这个分页的数据
        $list = $this->model
            ->field('id,organ_name')
            ->with([
                'bcompanybin'=>function($query)use($real_where1){$query->where($real_where1);},
            ])
            ->where($where1)
            ->select();
        $json = json_encode((object)$list);
        $lists = json_decode($json, true);

        foreach ($lists as $k=> &$vo){
            $vo['bin_number']=count($vo['bcompanybin']);
            $vo['bin_origin_name']='租赁箱';
        }

        $bin_number = array_column($lists,'bin_number');//返回数组中指定的一列
        $ids = array_column($lists,'id');//返回数组中指定的一列
        array_multisort($bin_number,SORT_DESC,$ids,SORT_ASC,$lists);//对多个数组或多维数组进行排序
        /*
         * 过滤箱子是空的数组
         */
        $filteredLists=array_filter($lists,function ($v){
            return !empty($v['bcompanybin']);
        });

        //数组根据当前页码和每页数据获取当前页的数据
        $start=($page-1)*$pageSize;
        $filteredData=array_slice($filteredLists,$start,$pageSize);


        $result = ['total' => count($filteredLists), 'list' => $filteredData];
        return json($result);

    }

    /*
      * 相应箱型下面对应的堆场可用箱数量(只考虑箱型)
      */
    public function only_bin_type_yard(){
        $this->request->filter(['strip_tags','trim']);
        $params =$this->request->param();
        //如果发送的来源是Selectpage，则转发到Selectpage
        $real_where1=[];
        $where1=[];


        if(!empty($params['custom']['bin_type'])){
            $bin_type=$params['custom']['bin_type'];
            $bin_type_name= Type::where(['id'=>$bin_type])->value('name');

            $real_where1['bin_type']=$params['custom']['bin_type'];
            $real_where1['current_status']=1;
        }
        if(!empty($params['custom']['organ_type'])){
            $where1['organ_type']=$params['custom']['organ_type'];
        }
        if(!empty($params['organ_name'])){
            $where1['organ_name']=['like','%'.$params['organ_name'].'%'];
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        // 排序
        $page=$params['pageNumber'];
        $pageSize=$params['pageSize'];
        /* //总数
         $total = $this->model
             ->where($where1)
             ->count();*/

        //这个分页的数据
        $list = $this->model
            ->field('id,organ_name')
            ->with([
                'bin'=>function($query)use($real_where1){$query->where($real_where1);},
            ])
            ->where($where1)
            ->select();
        $json = json_encode((object)$list);
        $lists = json_decode($json, true);

        foreach ($lists as $k=> &$vo){
            $vo['bin_number']=count($vo['bin']);
            $vo['bin_type_name']=$bin_type_name;

        }

        $bin_number = array_column($lists,'bin_number');//返回数组中指定的一列
        $ids = array_column($lists,'id');//返回数组中指定的一列
        array_multisort($bin_number,SORT_DESC,$ids,SORT_ASC,$lists);//对多个数组或多维数组进行排序
        /*
         * 过滤箱子是空的数组
         */
        $filteredLists=array_filter($lists,function ($v){
            return !empty($v['bin']);
        });

        //数组根据当前页码和每页数据获取当前页的数据
        $start=($page-1)*$pageSize;
        $filteredData=array_slice($filteredLists,$start,$pageSize);


        $result = ['total' => count($filteredLists), 'list' => $filteredData];
        return json($result);

    }

}
